import {
  getCardDetails,
  removeCard,
  toMailList
} from "../../apis/card";
import {
  globalData
} from '../../utils/request';
const app = getApp();

Page({
  data: {
    cardId: null,
    cardInfo: {},
    isRequest: false,
    shareImage: ''
  },

  onLoad(options) {
    this.setData({
      ...options
    });
  },

  onShow() {
    this.getCardInfo(this.data.cardId);
  },

  onShareAppMessage() {
    return {
      title: this.data.cardInfo.userName + '的快名片',
      path: `/pages/cardDetails/index?type=share&cardId=${this.data.cardInfo.cardId}`,
      imageUrl: this.data.shareImage
    }
  },

  // 获取信息
  getCardInfo(id) {
    getCardDetails(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        if (!new RegExp('^https://').test(data.avatar) && !new RegExp('^http://').test(data.avatar)) data.avatar = app.globalData.url + data.avatar;
        if (data.imageList) data.imageList = data.imageList.map(v => {
          if (!new RegExp('^https://').test(v) && !new RegExp('^http://').test(v)) v = app.globalData.url + v;
          return v
        });
        this.setData({
          cardInfo: data
        });
        if (this.data.from === 'mailList' && data.relCardId != 0) {
          wx.getStorage({
            key: 'historyPreview',
            success: res => {
              let arr = JSON.parse(res.data);
              if (arr.some(v => v.cardId == data.relCardId || v.cardId == data.cardId)) arr.splice(arr.findIndex(v => v.cardId == data.relCardId || v.cardId == data.cardId), 1);
              arr.unshift(data);
              wx.setStorage({
                data: JSON.stringify(arr),
                key: 'historyPreview'
              });
            },
            fail: res => {
              let arr = [data];
              wx.setStorage({
                data: JSON.stringify(arr),
                key: 'historyPreview'
              });
            }
          });
        };
        setTimeout(() => {
          wx.getImageInfo({
            src: data.avatar,
            success: res => {
              let avatar = {
                path: res.path,
                width: res.width,
                height: res.height
              };
              this.canvasShareImage(avatar, data.userName, data.company, data.post ? data.post : '暂无', data.label);
            }
          });
        }, 500);
      };
    });
  },

  // 生成分享小卡片
  canvasShareImage(avatar, userName, company, post, label) {
    let cvs = wx.createCanvasContext('share');
    cvs.drawImage('../../images/share_bg.png', 0, 0, 420, 336);
    cvs.save();
    cvs.beginPath();
    cvs.arc(210, 70, 54, 0, Math.PI * 2, false);
    cvs.clip();
    if (avatar.width > avatar.height) {
      cvs.drawImage(avatar.path, (avatar.width - avatar.height) / 2, 0, avatar.height, avatar.height, 156, 16, 108, 108);
    } else if (avatar.width < avatar.height) {
      cvs.drawImage(avatar.path, 0, (avatar.height - avatar.width) / 2, avatar.width, avatar.width, 156, 16, 108, 108);
    } else {
      cvs.drawImage(avatar.path, 156, 16, 108, 108);
    };
    cvs.restore();
    cvs.setFillStyle('#fff');
    cvs.setFontSize(26);
    let nameWidth = cvs.measureText(userName).width;
    cvs.fillText(userName, 210 - nameWidth / 2, 164);

    cvs.setFillStyle('#f7f7f7');
    cvs.setFontSize(20);
    let postWidth = cvs.measureText(`${company} · ${post}`).width;
    cvs.fillText(`${company} · ${post}`, 210 - postWidth / 2, 200);

    if (label.length > 0) {
      cvs.setFillStyle('#fff');
      cvs.setFontSize(22);
      label = label.map(v => {
        return {
          labelName: '#' + v,
          labelWidth: cvs.measureText('#' + v).width
        }
      }).sort((a, b) => b.labelWidth - a.labelWidth);
      let lineWidth = cvs.measureText('　|　').width;
      switch (label.length) {
        case 1:
          cvs.fillText(label[0].labelName, 210 - label[0].labelWidth / 2, 260);
          break;
        case 2:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          break;
        case 3:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName, 210 - (label[2].labelWidth) / 2, 300);
          break;
        case 4:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName + '　|　' + label[3].labelName, 210 - (label[2].labelWidth + label[3].labelWidth + lineWidth) / 2, 300);
          break;
        case 5:
          cvs.fillText(label[0].labelName + '　|　' + label[1].labelName, 210 - (label[0].labelWidth + label[1].labelWidth + lineWidth) / 2, 260);
          cvs.fillText(label[2].labelName + '　|　' + label[3].labelName + '　|　' + label[4].labelName, 210 - (label[2].labelWidth + label[3].labelWidth + label[4].labelWidth + lineWidth * 2) / 2, 300);
          break;
        default:
          break;
      };
    };

    cvs.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'share',
        destWidth: '420',
        destHeight: '336',
        fileType: 'png',
        success: res => {
          this.setData({
            shareImage: res.tempFilePath
          });
        }
      });
    });
  },

  // 删除卡片
  deleteCard() {
    wx.showModal({
      title: '删除',
      content: '确定删除此名片吗',
      success: res => {
        if (res.confirm) {
          removeCard(this.data.cardId).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 1000,
                success: () => {
                  let timer = setTimeout(() => {
                    wx.navigateBack({
                      delta: 1,
                    });
                    clearTimeout(timer);
                  }, 1000);
                }
              });
            };
          });
        };
      }
    });
  },

  // 查看好友名片
  handlePreview() {
    wx.navigateTo({
      url: `/pages/cardPreview/index?from=mailList&type=otherPreview&cardId=${this.data.cardInfo.cardId}`
    });
  },

  previewImage(e) {
    let {
      index
    } = e.currentTarget.dataset;
    wx.previewImage({
      urls: this.data.cardInfo.imageList,
      current: this.data.cardInfo.imageList[index]
    });
  },

  // 编辑名片
  editCard() {
    wx.navigateTo({
      url: `/pages/editCard/index?type=otherEdit&cardId=${this.data.cardId}`
    });
  },

  // 拨打
  callDial() {
    if (this.data.joinCardId == 'null') {
      wx.showToast({
        title: '您不是该组成员，无法拨打电话',
        icon: 'none'
      });
      return
    };
    wx.makePhoneCall({
      phoneNumber: this.data.cardInfo.phone,
      success: res => {
        let data = {
          avatar: this.data.cardInfo.avatar,
          name: this.data.cardInfo.userName,
          phone: this.data.cardInfo.phone,
          firstPy: this.data.cardInfo.firstPy,
          date: new Date().getTime()
        };
        wx.getStorage({
          key: 'callLog',
          success: res => {
            let arr = JSON.parse(res.data);
            if (arr.some(v => v.phone == data.phone)) arr.splice(arr.findIndex(v => v.phone == data.phone), 1);
            arr.unshift(data);
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'callLog'
            });
          },
          fail: res => {
            let arr = [data];
            wx.setStorage({
              data: JSON.stringify(arr),
              key: 'callLog'
            });
          }
        });
      }
    });
  },
  // 复制号码
  copyPhone() {
    if (this.data.joinCardId == 'null') {
      wx.showToast({
        title: '您不是该组成员，无法复制手机号',
        icon: 'none'
      });
      return
    };
    wx.setClipboardData({
      data: this.data.cardInfo.phone,
      success: res => {
        wx.showToast({
          title: '已复制手机号',
          icon: 'success'
        });
      }
    });
  },

  bindgetuserinfo(e) {
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo;
      this.saveCard();
    };
  },
  // 保存名片
  saveCard() {
    if (this.data.from == 'swiper' && this.data.joinCardId == 'null') {
      wx.showToast({
        title: '您不是该组成员，无法保存名片',
        icon: 'none'
      });
      return
    };
    if (this.data.cardInfo.ableAdd) {
      if (this.data.isRequest) return
      this.setData({
        isRequest: true
      });
      toMailList(this.data.cardId).then(res => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '添加成功',
            icon: 'success',
            mask: true,
            duration: 1500
          });
          this.setData({
            isRequest: false,
            'cardInfo.ableAdd': false
          });
        };
      });
    } else {
      if (this.data.cardInfo.userId == globalData.userId) {
        wx.showToast({
          title: '这是自己的名片...',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '您已经保存过了...',
          icon: 'none'
        });
      };
    };
  }
})